package leetcode;

/**
 * <p></p>
 *
 * @author bin.zhang
 * <p/>
 * Revision History:
 * 2020/09/10, 初始化版本
 * @version 1.0
 **/
public class LongestPalindrome {


	public String longestPalindrome(String s) {
		if(s == null || s.isEmpty() || s.length() == 1) return s;
		int length = 0;
		int start = 0;
		char[] chars = s.toCharArray();
		int strLength = chars.length;
		for (int i = 0; i < strLength; i++) {
			if (i == strLength - 1) {
				break;
			}
			if (chars[i] == chars[i + 1]) {
				int left = i;
				int right = i + 1;
				while (left >= 0 && right < strLength && chars[left] == chars[right]) {
					left--;
					right++;
				}
				if (length < right - left + 1) {
					length = right - left + 1;
					start = left + 1;
				}
			}
			if (i >= 1 && chars[i - 1] == chars[i + 1]) {
				int left = i - 1;
				int right = i + 1;
				while (left >= 0 && right < strLength && chars[left] == chars[right]) {
					left--;
					right++;
				}
				if (length < right - left + 1) {
					length = right - left + 1;
					start = left + 1;
				}
			}
		}
		return length == 0 ? s.substring(0, 1) : s.substring(start, length + start - 2);
	}

	public static void main(String[] args) {
		System.out.println(new LongestPalindrome().longestPalindrome("ac"));
	}
}
